package cn.edu.tsinghua.xkk.entity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Iterator;

/**
 * this is the class for storing the page
 * @author shibei
 *
 */
public class XKKFile {
	
	XKKPage page;
	
	public XKKFile()
	{
		page = new XKKPage();
	}
	
	public XKKFile(XKKPage p)
	{
		this.page = p;
	}
	
	public XKKPage getPage()
	{
		return page;
	}
	
	public void setPage(XKKPage p)
	{
		this.page = p;
	}
	
	public void writeToFile(String path)
	{
		try
		{
			File parentPath = new File(path);
			if(false)
			{
				System.out.println("The argument is wrong");
			}
			else
			{
				if(!parentPath.exists())
					parentPath.mkdirs();
				File allPath = new File(path + page.ID);
				if(!allPath.exists())
				{
					allPath.createNewFile();
				}
				BufferedWriter bw = new BufferedWriter(new FileWriter(allPath));
				String content = "";
				content += "#ID:\n" + page.ID;
				content += "\n";
				content += "#URL:\n" + page.getURL();
				content += "\n";
				content += "#Title:\n" + page.getTitle();
				content += "\n";
				content += "#Type:\n" + page.getType();
				content += "\n";
				content += "#Connection flag:\n" + page.getConnection(); 
				content += "\n";
				content += "#Charset:\n" + page.getEncoding();
				content += "\n";
				content += "#All content:\n" + page.getAllContent();
				content += "\n";
				content += "#Children links:\n";
				for(Iterator it = this.page.linkChildren.iterator(); it.hasNext();)
				{
					content += it.next() + "\n";
				}
				content += "\n";
				bw.write(content);
				bw.close();
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static XKKPage creatNewPage(File f)
	{
		XKKPage p = new XKKPage();
		try
		{	
			if(!f.exists())
			{
				System.out.println("The file does not exist.");
				return null;
			}
			BufferedReader br = new BufferedReader(new FileReader(f));
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return p;
	}
}
